export default class GoodsSpecsMatrix {
	constructor(specs, skuList) {
		this.specs = specs;
		this.skuList = skuList;
		this.specValues = this.getSpecValues();
		this.matrix = this.generateMatrix();
	}

	/*
	 * 获取所有规格
	 */
	getSpecValues() {
		const specValues = [];
		for (const spec of this.specs) {
			const values = spec.values;
			specValues.push(...values);
		}
		return specValues;
	}

	/*
	 * 创建规格的邻接矩阵
	 */
	generateMatrix() {
		// 邻接矩阵初始化
		const matrix = Array.from({
			length: this.specValues.length
		}, () => {
			return Array.from({
				length: this.specValues.length
			}, () => 0);
		});

		// 处理sku的连线
		this.skuList.forEach(sku => {
			const skuSpecs = sku.spec;
			skuSpecs.forEach(attr1 => {
				const rowIndex = this.specValues.indexOf(attr1);
				if(rowIndex !== -1) {
					skuSpecs.forEach(attr2 => {
						if (attr1 !== attr2) {
							const colIndex = this.specValues.indexOf(attr2);
							if (colIndex > -1) matrix[rowIndex][colIndex] = 1;
						}
					})	
				}
			})
		});
		// 处理同规格的连线，自己也是可选的，所以都连上
		this.specs.forEach(spec => {
			spec.values.forEach(attr1 => {
				const rowIndex = this.specValues.indexOf(attr1);
				if(rowIndex !== -1) {
					spec.values.forEach(attr2 => {
						// if (attr1 !== attr2) {
							const colIndex = this.specValues.indexOf(attr2);
							if (colIndex > -1) matrix[rowIndex][colIndex] = 1;
						// }
					})	
				}
			})
		});
		return matrix;
	}
	
	/*
	 * 传入顶点数组，查询出可选规格
	 */
	getSpecsOptions(specs) {
		if (!specs || specs.every(str => !str)) {
			return this.specValues;
		} else {
			return specs.filter(str => str)
				.map(str => this.specValues.indexOf(str))
				.map(index => this.matrix[index])
				.reduce((result, array) => {
				return result.map((value, index) => value && array[index]);
				}, new Array(this.specValues.length).fill(1)).reduce((options, cur, index) => {
					if (cur === 1) options.push(this.specValues[index]);
					return options;
				}, []);
		}
	}
}